package com.markerhub.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.markerhub.Vo.MonthVo;
import com.markerhub.common.ContentType;
import com.markerhub.common.lang.Result;
import com.markerhub.config.AliConfig;
import com.markerhub.dto.Echarts;
import com.markerhub.dto.VisitsRecordDto;
import com.markerhub.entity.Verify;
import com.markerhub.entity.VisitsRecord;
import com.markerhub.mapper.VerifyMapper;
import com.markerhub.mapper.VisitsRecordMapper;
import com.markerhub.service.VisitsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.time.Month;
import java.time.Year;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MarkerHub
 * @since 2022-03-25
 */
@Service
@Slf4j
public class VisitsRecordServiceImpl extends ServiceImpl<VisitsRecordMapper, VisitsRecord> implements VisitsRecordService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    VisitsRecordService visitsRecordService;
    @Autowired
    VisitsRecordMapper visitsRecordMapper;
    @Autowired
    VerifyMapper verifyMapper;

    @Override
    public    List<int[]>  getMonthTotle() {
        int index=0;
        List<int[]> listadd=new ArrayList<>();
        int[] ints1 = new int[12];
        int[] ints2 = new int[12];
        Calendar currCal=Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR,currCal.get(Calendar.YEAR));
        Date time = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        calendar.roll(Calendar.DAY_OF_YEAR,-1);
        Date time1 = calendar.getTime();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM");
        String start = format.format(time);
        String end = format1.format(time1);
        List<MonthVo> list=visitsRecordMapper.monthvisits(start,end);
        List<MonthVo> list2=visitsRecordMapper.monthacchieves(start,end);

        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getMonth().charAt(5)=='1'){
              index=Integer.parseInt(list.get(i).getMonth().substring(5,7))-1;
            }else{
                index=list.get(i).getMonth().charAt(6)-'0'-1;
            }
               ints1[index]=list.get(i).getC();
        }
        for (int i = 0; i < list2.size(); i++) {
            if(list2.get(i).getMonth().charAt(5)=='1'){
                index=Integer.parseInt(list2.get(i).getMonth().substring(5,7))-1;
            }else{
                index=list2.get(i).getMonth().charAt(6)-'0'-1;
            }
            ints2[index]=list2.get(i).getC();
        }
        listadd.add(ints1);
        listadd.add(ints2);
        return listadd;
    }

    @Override
    public List<Echarts> getYearTotle() {

        int year = Year.now().getValue();
        List<Echarts> list=new ArrayList<>();
        list.add(visitsRecordMapper.Unhandle(year));
        list.add(visitsRecordMapper.accept(year));
        list.add(visitsRecordMapper.forword(year));
        list.add(visitsRecordMapper.reject(year));
        list.add(visitsRecordMapper.handle(year));
        list.add(visitsRecordMapper.finish(year));
        list.add(visitsRecordMapper.acchieve(year));
        return list;
    }

    @Override
    public int[] getTotle() {
        int[] ints = new int[3];

        ints[0]=visitsRecordMapper.selectCount(new QueryWrapper<VisitsRecord>());
        ints[1]=visitsRecordMapper.selectCount(new QueryWrapper<VisitsRecord>().eq("status",5));
        ints[2]=visitsRecordMapper.selectCount(new QueryWrapper<VisitsRecord>().eq("status",6));
        return  ints;
    }

    @Override
    public Result updateRecord(VisitsRecordDto visitsRecordDto, MultipartFile multipartFile, Principal principal) {
        String url = "";
        log.info("员工信息: [{}]", visitsRecordDto.toString());
        if (multipartFile != null) {
            MultipartFile file = multipartFile;
            log.info("文件名: [{}]", file.getOriginalFilename());
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = AliConfig.END_POINT;
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = AliConfig.ACCESS_KEY_ID;
            String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
            String bucketName = AliConfig.BUCKET_NAME;
            String folder = AliConfig.FOLDER;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
                InputStream inputStream = file.getInputStream();
                //获取文件真实名称
                String originalFilename = file.getOriginalFilename();
                //重命名，防止相同文件出现覆盖
                //生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708c 需要替换成 f4f2e1a3391a4d5a94380c9f5d27708c
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //新的文件名
                originalFilename = uuid + originalFilename;
                //2、把文件按照日期进行分类
                String datePath = new DateTime().toString("yyyy/MM/dd");
                //拼接
                originalFilename = folder + "/" + datePath + "/" + originalFilename;
                // oss实现上传文件
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(ContentType.getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
                ossClient.putObject(bucketName, originalFilename, inputStream,objectMetadata);
                // 关闭OSSClient
                ossClient.shutdown();
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;

            } catch (Exception e) {
                e.printStackTrace();

            }
        }

        try {
            String today = String.format("%tF", new Date());
            UpdateWrapper<VisitsRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", visitsRecordDto.getId());
            VisitsRecord record = new VisitsRecord();
            record.setStatus(5);
            record.setHandler(principal.getName());
            record.setEnd(today);
            record.setRemarks(visitsRecordDto.getRemarks());

            record.setDocuments(url);
            visitsRecordService.update(record, updateWrapper);
        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail("操作失败");
        }
        return Result.succ("操作成功");

    }

    @Override
    public Result insetRecord(VisitsRecordDto visitsRecordDto, MultipartFile multipartFile) {
        VisitsRecord visitsRecord = new VisitsRecord();
        String url = "";
        log.info("员工信息: [{}]", visitsRecordDto.toString());
        if (multipartFile != null) {
            MultipartFile file = multipartFile;
            log.info("文件名: [{}]", file.getOriginalFilename());
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = AliConfig.END_POINT;
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = AliConfig.ACCESS_KEY_ID;
            String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
            String bucketName = AliConfig.BUCKET_NAME;
            String folder = AliConfig.FOLDER;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
                InputStream inputStream = file.getInputStream();
                //获取文件真实名称
                String originalFilename = file.getOriginalFilename();
                //重命名，防止相同文件出现覆盖
                //生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708c 需要替换成 f4f2e1a3391a4d5a94380c9f5d27708c
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //新的文件名
                originalFilename = uuid + originalFilename;
                //2、把文件按照日期进行分类
                String datePath = new DateTime().toString("yyyy/MM/dd");
                //拼接
                originalFilename = folder + "/" + datePath + "/" + originalFilename;
                // oss实现上传文件
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(ContentType.getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
                ossClient.putObject(bucketName, originalFilename, inputStream,objectMetadata);
                // 关闭OSSClient
                ossClient.shutdown();
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;

            } catch (Exception e) {
                e.printStackTrace();

            }
        }

        try {

            if (visitsRecordDto.getCasfile().equals("") && multipartFile == null) {
                return Result.fail("案件描述或信访文件不能为空");
            }
            visitsRecord.setFile(url);
            visitsRecord.setAddress(visitsRecordDto.getAddress());
            visitsRecord.setPhone(visitsRecordDto.getPhone());
            visitsRecord.setName(visitsRecordDto.getName());
            visitsRecord.setCasfile(visitsRecordDto.getCasfile());
            String today = String.format("%tF", new Date());
            visitsRecord.setTime(today);
            String a = String.valueOf((int) (Math.random() * 10000 + 10000));
            visitsRecord.setVerifyCode(a);
            visitsRecordMapper.insert(visitsRecord);
            Verify verify = new Verify();
            verify.setPhone(visitsRecordDto.getPhone());
            verify.setVerifyCode(a);
            int insert = verifyMapper.insert(verify);
            if (insert > 0) {
                redisUtil.set(verify.getPhone(), a, 60);
            }

        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail("登记失败");
        }
        return Result.succ("登记成功");
    }



}
